#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#include <QtDeclarative>
#ifdef Q_OS_SYMBIAN
#include <QSystemScreenSaver>
#endif
#include "nfcinfo.h"
#include "tagimagecache.h"

/*!
  \brief Search the children of the specified QML \a rootElement for
  an instance of the element with the specified \a objectName" property.

  \return if the element is found, an instance of the object.
  */
QObject* findQMLElement(QObject *rootElement, const QString &objectName)
{
    if(rootElement->objectName() == objectName) {
        return rootElement;
    }

    const QObjectList list = rootElement->children();
    for(QObjectList::const_iterator it=list.begin(); it!=list.end(); it++)
    {
        QObject *object = findQMLElement((*it), objectName);
        if(object != NULL) {
            return object;
        }
    }

    return NULL;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

#ifdef Q_OS_SYMBIAN
    // Translation for NFC Status messages
    QString locale = QLocale::system().name();

    QTranslator translator;
    translator.load(QString("nfcinfo_") + locale);
    app.installTranslator(&translator);

    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
#endif

    // Create a variable that stores the platform, to customize the
    // screen appearance in QML accordingly.
#if defined(Q_OS_SYMBIAN)
    int platformId = 0;
#elif defined(MEEGO_EDITION_HARMATTAN)
    int platformId = 1;
#elif defined(QT_SIMULATOR)
    int platformId = 2;
#else
    int platformId = 3;
#endif

    // Register the NfcInfo class to the QML environment
    qmlRegisterType<NfcInfo>("Nfc", 1, 0, "NfcInfo");

    // Setup QML Viewer
    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.rootContext()->setContextProperty("platform", platformId);

    // Register the image provider class to QML
    TagImageCache *tagImageCache = new TagImageCache();
    viewer.engine()->addImageProvider(QLatin1String("nfcimageprovider"), tagImageCache);

    viewer.setMainQmlFile(QLatin1String("qml/NfcInfo/main.qml"));

    // Inform the NfcInfo class about the image cache
    // The NfcInfo has been instantiated through QML, so retrieve its instance
    // through the QML object tree.
    NfcInfo *nfcInfoObj = viewer.rootObject()->findChild<NfcInfo*>("nfcInfoObj");
    if (nfcInfoObj) {
        nfcInfoObj->setImageCache(tagImageCache);
    }

    viewer.showExpanded();

#ifdef Q_OS_SYMBIAN
    // Prevent screensaver from kicking in on Symbian
    QSystemScreenSaver *screensaver = new QSystemScreenSaver ( &viewer );
    screensaver->setScreenSaverInhibit();
#endif

    return app.exec();
}
